console.log("Script文件加载成功");
toastr.options = {
    "closeButton": true,                        // 是否显示关闭按钮
    "progressBar":true,                         // 是否显示进度条
    "positionClass": "toast-top-right",         // 弹出窗的位置
    "showDuration": "500",                      // 显示的动画时间
    "hideDuration": "500",                      // 消失的动画时间
    "timeOut": "3000",                          // 弹窗展现时间
    "showEasing": "swing",                      // 显示时的动画缓冲方式
    "hideEasing": "linear",                     // 消失时的动画缓冲方式
    "showMethod": "fadeIn",                     // 显示时的动画方式
    "hideMethod": "fadeOut",                    // 消失时的动画方式
    "allowHtml":true,                           // 允许弹窗内容包含 HTML 语言
};
// 全局变量
let tabs = [];
let contents = [];
let currentTabType = 'student';          // 当前面板，默认 student
let currentPage = 1;                    // 当前页，默认第一页
let defaultPageSize = 10;               // 每页默认显示的记录数
let totalPages = 1;                     // 总页数，初始化为1
let totalRecordNum = 0;                 // 总记录数
let operationType = '';                  // 操作类型

// 页面加载时绑定初始化函数
document.addEventListener('DOMContentLoaded', initialize);

// 初始化入口函数（调用各个子模块）
function initialize() {
    console.log("【初始化】");
    CacheDOM();
    initializeDefaultTab();     // 默认激活第一个 tab
    setupEventListeners();   // 设置点击事件
}

/*-------------------------------------------------- 流程函数 ----------------------------------------------------------*/

// 缓存 DOM 组件
function CacheDOM() {
    tabs = document.querySelectorAll('.tab');
    contents = document.querySelectorAll('.content');
}

// 页面加载时激活默认tab
function initializeDefaultTab() {
    console.log("【initializeDefaultTab】设置默认TAB");
    let defaultTab = null;
    switch (currentTabType) {
        case "student":
            defaultTab = document.getElementById('student-tab');
            break;
        case "class":
            defaultTab = document.getElementById('class-tab');
            break;
        case "teacher":
            defaultTab = document.getElementById('teacher-tab');
            break;
        default:
            console.warn("未识别的tab类型: ", currentTabType);
            return;
    }
    if (defaultTab) {
        switchTab(defaultTab);
    } else {
        console.error("未能找到指定的tab元素: ", currentTabType);
    }
}

/* 设置监听器 */
function setupEventListeners() {
    console.log("【setupEventListeners】设置监听器");

    // 模块切换
    tabs.forEach(tab => {
        tab.addEventListener('click', function (e) {
            e.preventDefault(); // 阻止 a 标签默认跳转
            switchTab(tab); // 调用页面切换逻辑
        });
    });

    // 翻页区域
    const prevPageBtn = document.getElementById('prevPageBtn');
    if (prevPageBtn) {
        prevPageBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                updatePage();
            }
        });
    }
    const nextPageBtn = document.getElementById('nextPageBtn');
    if (nextPageBtn) {
        nextPageBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                currentPage++;
                updatePage();
            }
        });
    }

    // 跳转区域
    const jumpForm = document.getElementById('jumpForm');
    if (jumpForm) {
        jumpForm.addEventListener('submit', function(event) {
            event.preventDefault();
            const targetPageInput = document.getElementById('targetPage').value;
            const pageSizeInput = document.getElementById('pageSize').value;
            const targetPage = parseInt(targetPageInput, 10);
            const pageSize = parseInt(pageSizeInput, 10);
            console.log(`targetPage: ${targetPage}, pageSize: ${pageSize}, totalPages: ${totalPages}, totalRecordNum: ${totalRecordNum}`);
            const actualTotalPages = Math.ceil(totalRecordNum / pageSize);
            if (targetPage === currentPage && pageSize === defaultPageSize) {
                toastr.info("当前已在目标页面！");
            } else if (targetPage >= 1 && targetPage <= actualTotalPages) {
                currentPage = targetPage;
                defaultPageSize = pageSize;
                updatePage();
                toastr.success("跳转成功！");
            } else {
                toastr.warning("不合法的参数！")
            }
        })
    }

    // 模态窗口关闭按钮
    const closeStudentBtn = document.getElementById('close-student');
    if (closeStudentBtn) {
        closeStudentBtn.addEventListener('click', () => {
            hideModal("student-modal");
        })
    }
    const closeClassBtn = document.getElementById('close-class');
    if (closeClassBtn) {
        closeClassBtn.addEventListener('click', () => {
            hideModal("class-modal");
        })
    }
    const closeTeacherBtn = document.getElementById('close-teacher');
    if (closeTeacherBtn) {
        closeTeacherBtn.addEventListener('click', () => {
            hideModal("teacher-modal");
        })
    }
    const closeChooseTeacherBtn = document.getElementById('close-choose-teacher');
    if (closeChooseTeacherBtn) {
        closeChooseTeacherBtn.addEventListener('click', () => {
            hideModal("choose-teacher-modal");
        })
    }

    // 添加按钮
    const addStudentBtn = document.getElementById('add-student');
    if (addStudentBtn) {
        addStudentBtn.addEventListener('click', () => {
            operationType = 'insert';
            clearModal("student-modal")
            showModal("student-modal");
            getDataAndSetSelection("student-modal");
        })
    }
    const addClassBtn = document.getElementById('add-class');
    if (addClassBtn) {
        addClassBtn.addEventListener('click', () => {
            clearModal("class-modal");
            showModal("class-modal");
            getDataAndSetSelection("class-modal");
        })
    }
    const addTeacherBtn = document.getElementById('add-teacher');
    if (addTeacherBtn) {
        addTeacherBtn.addEventListener('click', () => {
            clearModal("teacher-modal");
            showModal("teacher-modal");
        })
    }

    // 学生模态窗口提交事件
    const studentForm = document.getElementById('s-data-form');
    if (studentForm) {
        studentForm.addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止默认提交行为
            const name = document.getElementById('name').value.trim();
            const gender = document.getElementById('gender').value;
            const ageInput = document.getElementById('age').value.trim();
            const classInput = document.getElementById('class').value.trim();
            // 构造 student 对象
            const student = {
                studentId: null,
                name: name,
                gender: gender,
                age: ageInput ? parseInt(ageInput) : null,
                classId: classInput ? parseInt(classInput) : null,
                createTime: null
            };
            if (operationType === 'insert') {
                console.log("开始insert学生");
                fetch('http://localhost:8080/stumanagement/student/add', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(student)
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 1) {
                            toastr.success("学生信息提交成功！");
                            document.getElementById('s-data-form').reset(); // 清空表单
                            hideModal("student-modal"); // 关闭弹窗
                            clearModal("student-modal");
                            updatePage(); // 刷新表格
                        } else {
                            toastr.warning('提交失败: ' + data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('【请求失败】', error);
                        alert('请求失败，请检查网络连接或联系管理员');
                    });
            } else if (operationType === 'update') {
                console.log("开始update学生");
                const studentId = document.getElementById('studentId').value;
                student.studentId = parseInt(studentId);
                fetch('http://localhost:8080/stumanagement/student/update', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(student)
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 1) {
                            toastr.success("学生信息更新成功！");
                        } else {
                            toastr.warning('更新失败: ' + data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('【更新请求失败】', error);
                        alert('更新失败，请检查网络连接或联系管理员');
                    })
                    .finally(() => {
                        hideModal("student-modal");
                        clearModal("student-modal");
                        updatePage();
                    });
            }
        });
    }

    // 班级模态窗口提交事件
    const classForm = document.getElementById('c-data-form');
    if (classForm) {
        classForm.addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止默认提交行为
            const clazzName = document.getElementById('className').value.trim();
            const grade = document.getElementById('grade').value.trim();
            // 构造 Clazz 对象
            const clazz = {
                clazzId: null,
                clazzName: clazzName,
                grade: grade ? grade : null,
                createTime: null
            };
            fetch('http://localhost:8080/stumanagement/clazz/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(clazz)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        toastr.success("班级信息提交成功！");
                        document.getElementById('c-data-form').reset();
                    } else {
                        toastr.warning('提交失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('【请求失败】', error);
                    alert('请求失败，请检查网络连接或联系管理员');
                })
                .finally(() => {
                    hideModal("class-modal");
                    clearModal("class-modal");
                    updatePage();
                });
        });
    }

    // 选择班主任模态窗口提交事件
    const chooseTeacherForm = document.getElementById('ct-data-form');
    if (chooseTeacherForm) {
        chooseTeacherForm.addEventListener('submit', function(event) {
            event.preventDefault();
            const clazzId = document.getElementById('clazzIdInput').value.trim();
            const teacherId = document.getElementById('headTeacher').value.trim();
            const params = new URLSearchParams();
            params.append('teacherId', teacherId);
            params.append('classId', clazzId);
            fetch('http://localhost:8080/stumanagement/teacher/linkClass', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: params
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 1) {
                        toastr.success('班主任设置成功');
                    } else {
                        toastr.warning('设置失败：' + (data.msg || "未知错误"));
                    }
                })
                .catch(err => {
                    console.error('请求失败:', err);
                    toastr.error('请求失败，请检查网络');
                })
                .finally(() => {
                    hideModal("choose-teacher-modal");
                    clearModal("choose-teacher-modal");
                    updatePage();
                });
        });
    }

    // 教师模态窗口提交事件
    const teacherForm = document.getElementById('t-data-form');
    if (teacherForm) {
        teacherForm.addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止默认提交行为
            // 获取并清理输入值
            const name = document.getElementById('teacherName').value.trim();
            const teacherGender = document.getElementById('teacherGender').value;
            const hireDate = document.getElementById('hireDate').value;
            // 构造 Teacher 对象
            const teacher = {
                teacherId: null,
                name: name,
                gender: teacherGender,
                hireDate: hireDate || null,
                createTime: null
            };
            // 发送请求
            fetch('http://localhost:8080/stumanagement/teacher/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(teacher)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 1) {
                        toastr.success("教师信息提交成功！");
                        teacherForm.reset(); // 清空表单
                    } else {
                        toastr.warning('提交失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('【请求失败】', error);
                    toastr.error('请求失败，请检查网络连接或联系管理员');
                })
                .finally(() => {
                    hideModal("teacher-modal");
                    updatePage();
                });
        });
    }
}

/*-------------------------------------------------- 功能函数 ----------------------------------------------------------*/

// 页面切换逻辑
function switchTab(tab) {
    console.log(`【switchTab】切换至TAB: ${tab.getAttribute('id')}`);
    const tabId = tab.getAttribute('id');
    switch (tabId) {
        case 'student-tab':
            currentTabType = 'student';
            break;
        case 'class-tab':
            currentTabType = 'class';
            break;
        case 'teacher-tab':
            currentTabType = 'teacher';
            break;
    }
    // 移除所有 tab 的 active 类
    tabs.forEach(t => t.classList.remove('active'));
    // 隐藏所有内容区域
    contents.forEach(c => c.classList.remove('active'));
    // 给当前 tab 添加 active 类
    tab.classList.add('active');
    // 显示对应的内容面板
    const targetId = tab.getAttribute('href');
    const targetContent = document.querySelector(targetId);
    if (targetContent) {
        targetContent.classList.add('active');
    }
    // 切换面板更新页码
    currentPage = 1;
    // 根据当前 TAB 加载数据
    updatePage();
}

// 请求后端接口获取相对应数据
function updatePage() {
    console.log(`【updatePage请求第${currentPage}页，每页${defaultPageSize}条数据， 当前面板类型：${currentTabType}`);
    switch (currentTabType) {
        case 'student':getStudentData();break;
        case 'class':getClassData();break;
        case 'teacher':getTeacherData();break;
    }
    updateJumpArea();
}

// 获取学生数据
function getStudentData() {
    fetch(`http://localhost:8080/stumanagement/student/page?page=${currentPage}&pageSize=${defaultPageSize}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误！状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log("【updatePage】收到响应数据", data);
            // 假设后端返回的数据结构如上所示
            if (data.code === 1 && data.msg === "success") {
                totalRecordNum = data.data.total;
                renderStudentTable(data.data.records); // 使用data下的records字段渲染表格
                updatePaginationInfo(totalRecordNum); // 更新分页信息
                updatePaginationButton(); // 更新翻页按钮
            } else {
                console.error("【updatePage】数据加载失败：", data.msg);
            }
        })
        .catch(error => {
            console.error("【updatePage】请求失败:", error);
        });
}

// 渲染学生表格
function renderStudentTable(students) {
    console.log(`【renderStudentTable】渲染学生列表，共${students.length}条`);
    const tbody = document.getElementById('student-list');
    tbody.innerHTML = ''; // 清空现有内容
    // 空值判断
    if (!students || students.length === 0) {
        const emptyRow = `
            <tr>
                <td colspan="7" style="text-align:center;">暂无数据，请先添加</td>
            </tr>
        `;
        tbody.insertAdjacentHTML('beforeend', emptyRow);
        return;
    }
    students.forEach(student => {
        let createTime = new Date(student.createTime).toLocaleString(); // 转换为本地时间格式
        let row = `<tr>
                    <td>${student.studentId}</td>
                    <td>${student.name}</td>
                    <td>${student.gender}</td>
                    <td>${student.age}</td>
                    <td>${student.className}</td>
                    <td>${createTime}</td>
                    <td class="action-area">
                        <button class="customized-button edit-btn" data-id="${student.studentId}">修改</button>
                        <button class="customized-button delete-btn" data-id="${student.studentId}">删除</button>
                    </td>
                  </tr>`;
        tbody.insertAdjacentHTML('beforeend', row);
    });
    // 先移除旧的监听器再绑定新的监听器
    tbody.removeEventListener('click', handleStudentTbodyClick);
    tbody.addEventListener('click', handleStudentTbodyClick);
}

// 获取班级数据
function getClassData() {
    fetch(`http://localhost:8080/stumanagement/clazz/page?page=${currentPage}&pageSize=${defaultPageSize}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误！状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log("【updatePage】收到响应数据", data);
            if (data.code === 1 && data.msg === "success") {
                totalRecordNum = data.data.total;
                renderClassTable(data.data.records); // 使用data下的records字段渲染表格
                updatePaginationInfo(totalRecordNum); // 更新分页信息
                updatePaginationButton(); // 更新翻页按钮
            } else {
                console.error("【updatePage】数据加载失败：", data.msg);
            }
        })
        .catch(error => {
            console.error("【updatePage】请求失败:", error);
        });
}

// 渲染班级表格
function renderClassTable(classes) {
    console.log(`【renderClassTable】渲染班级列表，共${classes.length}条`);
    const tbody = document.getElementById('class-list');
    tbody.innerHTML = ''; // 清空现有内容
    // 空值判断
    if (!classes || classes.length === 0) {
        const emptyRow = `
            <tr>
                <td colspan="7" style="text-align:center;">暂无数据，请先添加</td>
            </tr>
        `;
        tbody.insertAdjacentHTML('beforeend', emptyRow);
        return;
    }
    classes.forEach(clazz => {
        let createTime = clazz.createTime ? new Date(clazz.createTime).toLocaleString() : '--';
        // 判断是否有班主任名称，没有则显示设置按钮；有则显示班主任名称和取消关联按钮
        let teacherCellContent;
        if (clazz.teacherName && clazz.teacherId) { // 确保 teacherId 存在
            teacherCellContent = `
                <span>${clazz.teacherName}</span>
                <button class="customized-button unset-teacher-btn" data-id="${clazz.clazzId}" data-teacher-id="${clazz.teacherId}">取消关联</button>`;
        } else {
            teacherCellContent = `
                <button class="customized-button set-teacher-btn" data-id="${clazz.clazzId}">设置班主任</button>`;
        }
        let row = `
            <tr>
                <td>${clazz.clazzId}</td>
                <td>${clazz.clazzName}</td>
                <td>${clazz.grade}</td>
                <td>${teacherCellContent}</td>
                <td>${createTime}</td>
            </tr>`;
        tbody.insertAdjacentHTML('beforeend', row);
    });
    // 移除旧的监听器并绑定新的
    tbody.removeEventListener('click', handleClassTbodyClick);
    tbody.addEventListener('click', handleClassTbodyClick);
}

// 获取教师数据
function getTeacherData() {
    fetch(`http://localhost:8080/stumanagement/teacher/page?page=${currentPage}&pageSize=${defaultPageSize}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误！状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log("【updatePage】收到响应数据", data);
            if (data.code === 1 && data.msg === "success") {
                totalRecordNum = data.data.total;
                renderTeacherTable(data.data.records); // 使用data下的records字段渲染表格
                updatePaginationInfo(totalRecordNum); // 更新分页信息
                updatePaginationButton(); // 更新翻页按钮
            } else {
                console.error("【updatePage】数据加载失败：", data.msg);
            }
        })
        .catch(error => {
            console.error("【updatePage】请求失败:", error);
        });
}

// 渲染教师表格
function renderTeacherTable(teachers) {
    console.log(`【renderTeacherTable】渲染教师列表，共${teachers.length}条`);
    const tbody = document.getElementById('teacher-list');
    tbody.innerHTML = ''; // 清空现有内容
    // 空值判断
    if (!teachers || teachers.length === 0) {
        const emptyRow = `
            <tr>
                <td colspan="7" style="text-align:center;">暂无数据，请先添加</td>
            </tr>
        `;
        tbody.insertAdjacentHTML('beforeend', emptyRow);
        return;
    }
    teachers.forEach(teacher => {
        let createTime = teacher.createTime ? new Date(teacher.createTime).toLocaleString() : '未知';
        let hireDate = typeof teacher.hireDate === 'string' || teacher.hireDate instanceof String
            ? new Date(teacher.hireDate).toLocaleDateString() : '未知';
        let row = `<tr>
                    <td>${teacher.teacherId}</td>
                    <td>${teacher.name}</td>
                    <td>${teacher.gender}</td>
                    <td>${hireDate}</td>
                    <td>${createTime}</td>
                  </tr>`;
        tbody.insertAdjacentHTML('beforeend', row);
    });
    /* 等待后添加点击事件 */
}

// 更新分页信息
function updatePaginationInfo(total) {
    console.log(`【updatePaginationInfo】总记录数: ${total}, 当前页: ${currentPage}`);
    totalPages = Math.ceil(total / defaultPageSize);
    if (totalPages > 0) {
        document.getElementById('pageInfo').innerText = `第 ${currentPage} 页，共 ${totalPages} 页`;
    } else {
        document.getElementById('pageInfo').innerText = `无数据，共 ${totalPages} 页`;
    }
}

// 更新翻页按钮
function updatePaginationButton() {
    console.log(`【updatePaginationButton】当前页码：${currentPage}，当前总页数：${totalPages}`)
    prevPageBtn.disabled = currentPage <= 1;
    nextPageBtn.disabled = currentPage >= totalPages;
}

// 更新跳转区域
function updateJumpArea() {
    document.getElementById('targetPage').value = currentPage;
    document.getElementById('pageSize').value = defaultPageSize;
}

// 恢复模态框状态
function clearModal(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    switch (modalId) {
        case "student-modal":
            // 清空输入框
            const nameInput = document.getElementById('name');
            if (nameInput) nameInput.value = '';
            const ageInput = document.getElementById('age');
            if (ageInput) ageInput.value = '';
            const genderSelect = document.getElementById('gender');
            if (genderSelect) genderSelect.selectedIndex = 0;
            const classSelect = document.getElementById('class');
            if (classSelect) classSelect.selectedIndex = 0;
            // 移除 studentId 隐藏字段
            const hiddenInput = document.getElementById('studentId');
            if (hiddenInput) hiddenInput.remove();
            // 恢复模态框标题
            const modalTitle = modal.querySelector("h2");
            if (modalTitle) modalTitle.textContent = "添加学生";
            break;

        case "class-modal":
            // 清空输入框
            const clazzName = document.getElementById('className');
            if (clazzName) clazzName.value = '';
            const grade = document.getElementById('grade');
            if (grade) grade.value = '';
            break;

        case "choose-teacher-modal":
            // 清空输入框
            const headTeacher = document.getElementById('headTeacher');
            if (headTeacher) headTeacher.selectedIndex = 0;
            // 置空隐藏字段
            const clazzIdInput = document.getElementById('clazzIdInput');
            if (clazzIdInput) clazzIdInput.value = '';
            break;

        case "teacher-modal":
            const teacherNameInput = document.getElementById('teacherName');
            if (teacherNameInput) teacherNameInput.value = '';
            const teacherGenderSelect = document.getElementById('teacherGender');
            if (teacherGenderSelect) teacherGenderSelect.selectedIndex = 0;
            const hireDateInput = document.getElementById('hireDate');
            if (hireDateInput) hireDateInput.value = '';
            break;

        default:
            console.warn(`未知的模态框 ID: ${modalId}`);
    }
}

// 显示模态窗口
function showModal(modalId) {
    document.getElementById(modalId).style.display = 'block';
}

// 隐藏模态窗口
function hideModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// 获取并设置选项列表
function getDataAndSetSelection(modalId) {
    switch (modalId) {
        case 'student-modal':
            // 获取下拉框元素
            const classSelect = document.getElementById("class");
            // 发起请求获取班级列表
            fetch("http://localhost:8080/stumanagement/clazz/select")
                .then(response => response.json())
                .then(result => {
                    classSelect.innerHTML = ""; // 清空当前内容
                    if (result.code === 1 && Array.isArray(result.data)) {
                        result.data.forEach(clazz => {
                            const option = document.createElement("option");
                            option.value = clazz.clazzId;
                            option.textContent = clazz.clazzName;
                            classSelect.appendChild(option);
                        });
                    } else {
                        const option = document.createElement("option");
                        option.value = "";
                        option.textContent = "暂无班级";
                        classSelect.appendChild(option);
                    }
                })
                .catch(error => {
                    console.error("【加载班级失败】", error);
                    classSelect.innerHTML = '<option value="">加载失败</option>';
                });
            break;

        case 'class-modal':
            // 如果你需要在这里处理其他逻辑，可以添加
            break;
    }
}

// 处理学生操作区点击事件
function handleStudentTbodyClick(event) {
    const target = event.target;
    if (!(target instanceof Element)) return;
    const editBtn = target.closest('.edit-btn');
    const deleteBtn = target.closest('.delete-btn');
    if (editBtn) { // 修改按钮事件
        const studentId = editBtn.getAttribute('data-id');
        operationType = 'update';
        handleStudentEditButtonClick(studentId);
    } else if (deleteBtn) { // 删除按钮事件
        const studentId = deleteBtn.getAttribute('data-id');
        handleStudentDeleteButtonClick(studentId);
    }
}

// 处理“修改学生”按钮点击事件
function handleStudentEditButtonClick(studentId) {
    clearModal("student-modal");
    const modal = document.getElementById("student-modal");
    const modalTitle = modal.querySelector("h2");
    modalTitle.textContent = "编辑学生";
    // 插入 studentId 隐藏字段
    let hiddenInput = document.getElementById('studentId');
    if (!hiddenInput) {
        hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.id = 'studentId';
        hiddenInput.name = 'studentId';
        modalTitle.insertAdjacentElement('afterend', hiddenInput);
    }
    hiddenInput.value = studentId;
    const classSelect = document.getElementById("class");
    // 加载班级列表
    fetch("http://localhost:8080/stumanagement/clazz/select")
        .then(response => response.json())
        .then(clazzResult => {
            classSelect.innerHTML = ""; // 清空当前内容
            if (clazzResult.code === 1 && Array.isArray(clazzResult.data)) {
                clazzResult.data.forEach(clazz => {
                    const option = document.createElement("option");
                    option.value = clazz.clazzId;
                    option.textContent = clazz.clazzName;
                    classSelect.appendChild(option);
                });
            } else {
                const option = document.createElement("option");
                option.value = "";
                option.textContent = "暂无班级";
                classSelect.appendChild(option);
            }
            // 获取学生信息
            return fetch(`http://localhost:8080/stumanagement/student/search/${studentId}`);
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('获取学生信息失败');
            }
            return response.json();
        })
        .then(studentResult => {
            const student = studentResult.data;
            document.getElementById('name').value = student.name;
            document.getElementById('gender').value = student.gender;
            document.getElementById('age').value = student.age;
            // 设置班级下拉框选中项
            classSelect.value = student.classId;
            showModal("student-modal"); // 显示模态框
        })
        .catch(error => {
            console.error('操作过程中出现问题: ', error);
        });
}

// 处理“删除学生”按钮点击事件
function handleStudentDeleteButtonClick(studentId) {
    if (confirm("确定要删除该学生吗？")) {
        fetch(`http://localhost:8080/stumanagement/student/delete`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify([studentId])
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    toastr.success("删除成功！");
                    updatePage();
                } else {
                    toastr.warning("删除失败：" + data.msg);
                }
            })
            .catch(error => {
                console.error("删除出错：", error);
                alert("网络错误，请重试");
            });
    }
}

// 处理班级操作区点击事件
function handleClassTbodyClick(event) {
    const btn = event.target.closest('.set-teacher-btn, .unset-teacher-btn');
    if (!btn) return;
    const clazzId = btn.getAttribute('data-id');
    if (btn.classList.contains('set-teacher-btn')) {
        handleSetTeacherBtnClick(clazzId);
    } else if (btn.classList.contains('unset-teacher-btn')) {
        const teacherId = btn.getAttribute('data-teacher-id');
        handleUnsetTeacherBtnClick(teacherId, clazzId);
    }
}

// 处理“设置班主任”按钮点击事件
function handleSetTeacherBtnClick(clazzId) {
    // 清空模态框内容
    clearModal("choose-teacher-modal");
    document.getElementById('clazzIdInput').value = clazzId;

    // 获取教师列表
    fetch('http://localhost:8080/stumanagement/teacher/select')
        .then(response => {
            if (!response.ok) {
                throw new Error('获取教师列表失败');
            }
            return response.json();
        })
        .then(data => {
            // 检查 code 是否为 1 表示成功
            if (data.code !== 1) {
                throw new Error('获取教师列表失败：' + data.msg);
            }

            const teachers = data.data; // 提取真正的教师数组
            if (!Array.isArray(teachers)) {
                throw new Error('返回的数据不是数组');
            }

            const select = document.getElementById('headTeacher');
            select.innerHTML = ''; // 清空旧选项

            if (teachers.length === 0) {
                const option = document.createElement('option');
                option.textContent = '暂无教师';
                option.disabled = true;
                select.appendChild(option);
            } else {
                teachers.forEach(teacher => {
                    const option = document.createElement('option');
                    option.value = teacher.teacherId;
                    option.textContent = teacher.name;
                    select.appendChild(option);
                });
            }

            showModal("choose-teacher-modal");
        })
        .catch(error => {
            console.error('获取教师列表失败:', error);
            alert('加载教师列表失败，请刷新重试');
        });
}

// 处理“取消绑定班主任”按钮点击事件
function handleUnsetTeacherBtnClick(teacherId, clazzId) {
    if (confirm("确定要取消绑定班主任吗？")) {
        const url = `http://localhost:8080/stumanagement/teacher/unlinkClass?teacherId=${teacherId}&classId=${clazzId}`;
        fetch(url, {
            method: 'DELETE'
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    toastr.success("取消绑定成功");
                    updatePage();
                } else {
                    toastr.warning("取消绑定失败，原因：" + data.msg);
                }
            })
            .catch(err => {
                console.error('请求失败:', err);
                alert('请求失败，请检查网络');
            });
    }
}